/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Ucop/AtExit.h"
#include <cassert>
#include "Ucop/System/LockGuard.h"
using Ucop::System::Mutex;
using Ucop::System::LockGuard;


namespace Ucop {

    AtExit* AtExit::_Myinstance = NULL;

    AtExit::AtExit(void)
        : _Mycallbacks()
        , _MycallbacksLock()
    {
        UCOP_ASSERT(!_Myinstance);
        _Myinstance = this;
    }

    AtExit::~AtExit(void)
    {
        UCOP_LOCK_GURAD_ASSERT(_MycallbacksLock);
        while (!_Mycallbacks.empty())
        {
            _Mycallbacks.top()();
            _Mycallbacks.pop();
        }
    }

    void AtExit::_Push(EXIT_CALLBACK _Callback)
    {
        UCOP_LOCK_GURAD_ASSERT(_MycallbacksLock);
        _Mycallbacks.push(_Callback);
    }

    void AtExit::Push(EXIT_CALLBACK _Callback)
    {
        UCOP_ASSERT(_Myinstance);
        _Myinstance->_Push(_Callback);
    }
}